package validater

import (
	"reflect"
	"strings"

	logger "gitee.com/krio/ginc/example/core/lib/logger/zaplog"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
)

const language = "zh" // 验证提示语言

var (
	validate *validator.Validate
	trans    ut.Translator
)

// api入参验证
func init() {
	validate = validator.New()
	// 获取struct tag里自定义的label作为字段名
	validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		label := field.Tag.Get("label")
		if label == "" {
			return field.Name
		}
		return label
	})

	var (
		err error
		lt  = zh.New()
		uni = ut.New(lt, lt)
	)
	trans, _ = uni.GetTranslator(language)
	// 注册翻译器
	switch language {
	case "zh":
		err = zhTranslations.RegisterDefaultTranslations(validate, trans)
	default:
		err = enTranslations.RegisterDefaultTranslations(validate, trans)
	}
	if err != nil {
		logger.Fatal(err)
	}
}

// translate 错误数组整合返回
func translate(err error) string {
	var errList []string
	for _, e := range err.(validator.ValidationErrors) {
		// can translate each error one at a time.
		errList = append(errList, e.Translate(trans))
	}

	return strings.Join(errList, "|")
}

// RequestValidate 接口请求参数验证
func RequestValidate(req interface{}) string {
	if err := validate.Struct(req); err != nil {
		return translate(err)
	}

	return ""
}
